#include "cpuclock.h"
#include <QFile>
#include <QTextStream>

CpuClock::CpuClock(QObject *parent) : QObject(parent) 
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &CpuClock::updateCpuClock);
    timer->start(1000);
}

CpuClock::~CpuClock() 
{
    if (timer != nullptr)
    {
        if (timer->isActive())
        {
            timer->stop();
        }
    }
}

QString CpuClock::getCpuClock() {
    QFile file("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return "无法打开文件";

    QTextStream in(&file);
    QString line = in.readLine();
    bool ok;
    int freqKHz = line.toInt(&ok);
    if (ok) {
        double freqGHz = freqKHz / 1000000.0;
        return QString("%1 GHz").arg(freqGHz, 0, 'f', 2);
    }

    return "未找到 CPU 频率信息";
}

void CpuClock::updateCpuClock() {
    emit clockChanged();
}
